layui.use(['table', 'form', 'element','jquery', 'laydate','layer','laytpl'], function () {
    var table = layui.table;         //表格
    var form = layui.form;           //表单
    var layer = layui.layer;         //弹层
    var $ = layui.jquery;
    var element = layui.element;
    var laytpl = layui.laytpl;
    element.render();
    var load = loading("数据加载中...")
    table.render({
        elem: '#user-table'
        ,height: 'full-300'
        ,url: '/user/getAllUser'
        ,method:'get'
        , height: 'full-300'
        , page: true
        , request:{
            pageName:'pageNo',
            limitName:'PageSize'
        }
        , cellMinWidth: 90
        ,    limit : 10
        ,    limits : [5, 10, 15, 20, 25]
        , cols: [[
            {type: 'checkbox'}
            , {field: 'id',column:'id', title: 'ID',width:50}
            , {field: 'username',column:'username', title: '用户名',width:100}
            , {field: 'email',column:'email', title: '邮箱',width:180}
            , {field: 'phone',column:'phone', title: '电话号码',width:120}
            , {field: 'recentlylanded',column:'recentlylanded', title: '注册时间',width:200}
            , {field: 'gender',column:'gender', title: '性别',width:90}
            , {field: 'rid',column:'rid', title: '角色',width:100,templet:function (res) {
                var rid=res.role.rid;
                if (rid===1){
                    return '普通用户';
                }else if(rid===2){
                    return '管理员';
                }else if (rid===3){
                    return '超级管理员'
                }
                }}
            , {fixed: 'right',title: '操作',  align:'center', toolbar: '#toolBar'} //工具栏
        ]],

        done: function (res, curr, count) {
            $('#totalProjectNumber').text("共有数据："+count+" 条");
            layer.close(load);
            //如果是异步请求数据方式，res即为你接口返回的信息。
            //如果是直接赋值的方式，res即为：{data: [], count: 99} data为当前页数据、count为数据总长度
            $("[data-field='gender']").children().each(function () {
                if ($(this).text() == 'male') {
                    $(this).text('男');
                } else if ($(this).text() == 'woman') {
                    $(this).text('女');
                }
            });
        }

    });
    //条件查询
    form.on('submit(sreach)', function(data){
        table.reload('user-table',{
            url:"/user/getAllUser",
            page: {
                curr: 1 //重新从第 1 页开始
            },
            where:{
                email:data.field.email,
                username:data.field.username,
                phone:data.field.phone
            }
        });
    });
    //刷新按钮事件
    $("#refresh").click(function () {
        table.reload('user-table', {
            url: "/user/getAllUser",
            page: {
                curr: 1 //重新从第 1 页开始
            }
        })
    })


    //工具栏监听事件
    table.on('tool(user-table)', function(obj) {
        var data = obj.data;
        var layEvent=obj.event;
        if(layEvent == 'del') {
            layer.confirm('确定删除本行数据吗',function (index) {
                layer.close(index);//关闭弹框
                var loade=loading("加载中...")
                $.ajax({
                    type:'delete',
                    url:'/user/delUser/'+data.id,
                    success:function (data) {
                        if (data.code==200){
                            layer.close(loade);
                            layer.msg('删除成功啦', { icon: 1 }, { time: 2000 });
                            obj.del();//删除对应行的结构
                        }else{
                            layer.msg('删除失败，请稍后重试', { icon: 2 }, { time: 2000 });
                        }
                    },
                    error:function (data) {
                        layer.msg('系统异常！', { icon: 2 }, { time: 2000 });
                    }
                })
            })
        }else if (layEvent=='edit') {
            data.list = layui.data('user-table').list;
            var content = $("#UpduserTemplateList").html();
            laytpl(content).render(data, function (string) {
                layer.open({
                    type: 1,
                    title: "修改用户信息",
                    area: ['600px', '400px'], //宽高
                    content: string
                });
                form.render('radio');
                form.render('select');
            });
            return false;
        }
    });
    //新增用户点击事件
    $("#userAdd").click(function () {
        var data = [];
        data.list = layui.data('user-table').list;
        var content = $("#AdduserTemplateList").html();
        laytpl(content).render(data, function (string) {
            layer.open({
                type: 1,
                title: "添加用户信息",
                area: ['600px', '500px'], //宽高
                content: string
            });
            form.render('radio');
            form.render('select');
            form.verify({
                password:function (value) {
                    var pwd = /^^(?![^a-z]+$)(?![^A-Z]+$)(?!\D+$).{8,15}$$/;
                    if(pwd.test(value)!=true){
                        $("input[name=password]").val('');
                        $("input[name=confirmPwd]").val('');
                        return '密码格式入错误,必须有小写字母和数字组合,长度为8~15';
                    }
                },
                confirmPwd:function (value) {
                    var pwd=$("input[name=password]").val();
                    if (pwd!=value) {
                        $("input[name=password]").val('');
                        $("input[name=confirmPwd]").val('');
                        return '两次密码不一致,请重新输入';
                    }
                },
                email:function (value) {
                    var email=/^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,5}$/;
                    if (email.test(value)!=true){
                        return '请输入正确的邮箱格式!';
                    }
                }
            })
        });

    });
    //表单提交监听
    layui.use('form', function(){
        var form = layui.form;
        //新增监听提交
        form.on('submit(add_sumbit)', function(data){
            $.post(
                "user/insert",
                $(data.form).serialize(),
                function (obj) {
                    if (obj.code == 0) {
                        layer.msg('新增成功啦', { icon: 1 }, { time: 2000 })
                        layer.closeAll('page');
                        table.reload('user-table',{});
                    }
                    else {
                        layer.msg('新增失败！', { icon: 1 }, { time: 2000 })
                    }
                }
            );
            return false;
        });
    });
    //修改按钮监听事件
    layui.use('form', function(){
        var form = layui.form;
        form.on('submit(upd_sumbit)', function(data){
            $.ajax({
                type: 'put',
                url: '/user/update',
                data: $(data.form).serialize(),
                success: function (obj) {
                    if (obj.code == 0) {
                        layer.msg('修改成功啦！', {icon: 1}, {time: 2000})
                        layer.closeAll('page');
                        table.reload('user-table', {});
                    }
                    else {
                        layer.msg('修改失败！', {icon: 1}, {time: 2000})
                    }
                }
            })
        });
    });
    //Execle导出
    $('#export').click(function (data) {
        loading = layer.load(1, {shade: [0.3, '#fff']});
        var $ = layui.jquery;
        var excel = layui.excel;
        $.ajax({
            url: 'user/getExecelList',
            dataType: 'json',
            data: {
                datas:JSON.stringify(data.field)
            },
            success: function(res) {
                layer.close(loading);
                layer.msg(res.msg);
                // 假如返回的 res.data 是需要导出的列表数据
                console.log(res.data);//
                // 1. 数组头部新增表头
                res.data.unshift({id: 'ID',phone: '电话',username:'用户名',gender:'性别',birthday:'生日',email:'邮箱',recentlylanded:'注册时间',rname:'权限'});
                // 3. 执行导出函数，系统会弹出弹框
                excel.exportExcel({
                    sheet1: res.data
                }, '用户信息.xlsx', 'xlsx');
            },
            error:function(res){
                layer.close(loading);
                layer.msg(res.msg);
            }
        });
    })
    //批量删除点击事件
    $("#dels").click(function () {
        var checkStatus = table.checkStatus('user-table');
        if (checkStatus.data.length == 0) {
            parent.layer.msg('请先选择要删除的数据行！', {icon: 2});
            return;
        }
        var ids = "";
        for (var i = 0; i < checkStatus.data.length; i++) {
            ids += checkStatus.data[i].id + ",";
        }
        layer.confirm('确定删除id为'+ids+'的数据吗',function (index) {
            layer.close(index);//关闭弹框
            var loade=loading("加载中...")
            $.ajax({
                type: 'delete',
                url: '/user/delUser/' + ids,
                success:function (data) {
                    if (data.code==200){
                        layer.close(loade);
                        layer.msg('删除成功啦', { icon: 1 }, { time: 2000 });
                        table.reload('user-table',{});//重新加载table数据
                    }else{
                        layer.msg('删除失败，请稍后重试', { icon: 2 }, { time: 2000 });
                    }
                },
                error:function (data) {
                    layer.msg('系统异常', { icon: 2 }, { time: 2000 });
                }
            })
        })
    })

});

    //带字的loading方法
    function loading(content) {
        var index = layer.load(2, {
            shade: [0.2, '#fff'],
            content:content,
            success: function (layerContentStyle) {
                layerContentStyle.find('.layui-layer-content').css({
                    'padding-top': '35px',
                    'text-align': 'left',
                    'width': '120px'
                });
            }
        }, {time: 15 * 1000});
        return index;
    }
    //单选按钮

